import React, {useEffect, useState} from 'react'
import { Form, Button,Input, Modal, Row, Col,InputNumber,Switch,Upload,message} from 'antd'
import { connect } from 'umi'
import {UploadOutlined} from '@ant-design/icons';
import {getUploadUrl} from "@/utils/upload";
const FormItem = Form.Item
const { TextArea } = Input;

const formLayout = {
  labelCol: { span: 7 },
}

const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
}

const AddForm = (props) => {
  const { onSubmit, onCancel, loading,record,visible} = props
  const [form] = Form.useForm()
  const [fileUploadUrls,setFileUploadUrls] = useState([])
  const [fileName, setFileName] = useState(null)
  const [title,setTitle] = useState(null)

  useEffect(() => {
    if(record && visible){
      setTitle("编辑banner页")
      setFileUploadUrls([record.bannerUrl])
      form.setFieldsValue({...record,urlIds:record.bannerUrl});
    }else{
      setTitle("新增banner页")
    }
  }, [visible]);

  const onFormCancel = () => {
    setFileUploadUrls([]);
    form.resetFields();
    onCancel()
  };


  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields()
    form.resetFields()
    onSubmit({
      ...fieldsValue,
      bannerUrl:fileUploadUrls[0],
      isShow:fieldsValue.isShow?1:0,
      id:record && record.id
    })
    setFileUploadUrls([])
  }

  const fileList = {
    name: 'file',
    accept:'.jpg,.png,.jpeg,.BMP',
    action: getUploadUrl(),
    data: {name: fileName},
    beforeUpload(file) {
      setFileName(file.name)
    },
    onChange(res) {
      const {status} = res.file;
      if (status === 'done') {
        if (res.file.response.error) {
          message.success(`${res.file.response.error}`);
        } else {
          setFileUploadUrls([res.file.response ]);
          message.success(`${res.file.name} 文件上传成功`);
        }
      } else if (status === 'error') {
        message.error(`${res.file.name} 文件上传失败`);
      }
    },
    onRemove(info) {
      let urls = fileUploadUrls;
      let index = urls.indexOf(info.url);
      if (index > -1)
        urls.splice(index, 1);
      setFileUploadUrls(urls);
    }
  };

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="bannerTitle" label="轮播标题" rules={[{required: true, message: '轮播标题不能为空'}]}>
             <Input placeholder="请输入轮播标题"/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="url" label="跳转地址">
              <Input placeholder="请输入跳转地址"/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="orderNum" label="展示排序">
              <InputNumber min={0} max={10} placeholder="请输入展示排序" style={{width:'100%'}}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="urlIds" label="上传图片" rules={[{required: true, message: '上传图片不能为空'}]}>
              <Upload {...fileList}>
                <Button>
                  <UploadOutlined/> 点击上传图片
                </Button>
              </Upload>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="isShow" label="是否展示">
              <Switch checkedChildren="是" unCheckedChildren="否" defaultChecked={record && record.isShow === 1 ?true:false}/>
            </FormItem>
          </Col>
          <Col span={24}>
            <FormItem name="remarks" labelCol={{span: 2}} label="备注">
              <TextArea rows={4} className='widthStyle'/>
            </FormItem>
          </Col>
        </Row>
      </>
    )
  }

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        <Button type="primary" loading={loading} onClick={() => handleSubmit()}>提交</Button>
      </>
    )
  }

  return (
    <Modal
      width={1280}
      destroyOnClose
      title={title}
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      onClose={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{ paddingTop: '24px' }}
      >
        {renderContent()}
      </Form>
    </Modal>
  )
}

export default connect(() => ({
}))(AddForm)
